<?php

namespace App\Http\Controllers\applet_api;

use App\Http\Controllers\Controller;
use App\Models\AppCourse;
use App\Models\AppCourseType;
use App\Models\AppCourseVideo;
use App\Models\AppOrder;
use App\Models\VipOrder;
use Illuminate\Http\Request;

class CourseController extends Controller
{
    public function index(Request $Request)
    {
        $search = $Request->search;
        $level = $Request->level ?: 0;
        $pid = $Request->pid ?: 0;
        $limit = $Request->limit ?: 30;
        $page = $Request->page ?: 1;
        $page = $page * $limit - $limit;
        $sql = AppCourse::select('id','title','brief','clicks','cover','created_at','original_price','price','status','learns')->withCount('orders')->withCount('videos')->when($search, function ($query, $search) {
                    return $query->where('title','like', '%'.$search.'%');
                })
                ->when($pid, function ($query, $pid) {
                    return $query->where('pid', $pid);
                })
                ->when($level, function ($query, $level) {
                    return $query->where('level', $level);
                });
        $total = $sql->count();
        $data = $sql->skip($page)->take($limit)->orderBy('sort','asc')->get();
        return response()->json(['code' => '200', 'msg' => 'success','data'=>$data,'total'=>$total]);
    }

    public function info(Request $Request)
    {
        $data = AppCourse::with('videos')->with('informations')->withCount('orders')->where('id',$Request->id)->first();
        $data->auth = false;
        if($Request->uid){
            $order = AppOrder::select('id')->where('user_id',$Request->uid)->where('product_id',$Request->id)->where('type','course')->where('pay_status','success')->first();
            if($order){
                $data->auth = true;
            }
    
            //是否是vip
            $vip = VipOrder::with('vip')->where('uid',$Request->uid)->where('status',1)->orderBy('vip_id','desc')->first();
            $data->vip = [];
            if($vip){
                $data->auth = true;
                $data->vip = $vip->vip->auth;
            }
        }
        $data->increment('clicks');
        return response()->json(['code' => '200', 'msg' => 'success','data'=>$data]);
    }

    public function study(Request $Request)
    {
        $data = AppCourseVideo::find($Request->id);
        $data->increment('clicks');
        return response()->json(['code' => '200', 'msg' => 'success','data'=>$data]);
    }

    public function type(Request $Request)
    {
        $data = AppCourseType::get();
        return response()->json(['code' => '200', 'msg' => 'success','data'=>$data]);
    }

}
